from rest_framework.response import Response
from rest_framework.views import APIView
from . import models
from .serializer import *
import re



# 产品信息
class GoodsView(APIView):
    def get(self,request):
        uid=request.GET.get('uid','')

        if uid:
            data=[]
            goodqueryset = models.Goods.objects.all()
            for i in goodqueryset:
                data.append({'id':i.id,'title':i.title,'img':str(i.img),'price1':i.price2})
            return Response(data)
        else:
            # 1.获取所有的商品
            goodqueryset = models.Goods.objects.all()

            # 序列化
            obj=GoodsSerializer(goodqueryset,many=True)


            # 返回
            return Response(obj.data)




# 登录
class LoginView(APIView):
    def post(self,request):
        # 接收参数
        username=request.data.get('username')
        password=request.data.get('password')

        # 查库判断
        userobj=models.User.objects.filter(username=username,password=password).first()
        if userobj:
            return Response({'code':1000,'msg':'登录成功','data':userobj.id})
        return Response({'code':1000,'msg':'登录失败','data':''})



# 订单
class OrderView(APIView):
    # 获取xxx的订单
    def get(self,request):
        # 接收参数
        uid=request.GET.get('uid')

        # 查询订单
        orderqueryset=models.Order.objects.filter(user_id=uid).all()

        # 序列化
        obj=OrderSerializer1(orderqueryset,many=True)

        return Response(obj.data)



    # 添加
    def post(self,request):
        # 接收参数
        uid=request.data.get('uid')
        goodid=request.data.get('goodid')
        name=request.data.get('name')
        phone=request.data.get('phone')

        # 正则判断
        if not name:
            return Response({'code':1001,'msg':'姓名不能为空'})

        if not re.match(r'^1[3-9]{1}\d{9}$',phone):
            return Response({'code':1002,'msg':'手机号不合法'})

        # 构造数据
        data={
            'user':uid,
            'goods':goodid,
            'name':name,
            'phone':phone
        }

        obj=OrderSerializer(data=data)

        if obj.is_valid():
            obj.save()
            return Response({'code':1000,'msg':'订单添加成功'})

        print(obj.errors)
        return Response({'code': 1000, 'msg': '参数有误'})



